package com.haiheng.voiceandbook

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import android.widget.Toast
import androidx.cardview.widget.CardView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.android.material.appbar.AppBarLayout
import com.haiheng.bookmusic.base.BaseActivity
import com.haiheng.bookmusic.utils.GlideUtils
import com.haiheng.voiceandbook.Constants.Companion.taizhou_code
import com.haiheng.voiceandbook.adapter.BookAdapter
import com.haiheng.voiceandbook.adapter.MainTopAdapter
import com.haiheng.voiceandbook.commo.SettingDialog
import com.haiheng.voiceandbook.commo.VersionManager
import com.haiheng.voiceandbook.common.BookDto
import com.haiheng.voiceandbook.databinding.ActivityMainBinding
import com.haiheng.voiceandbook.dialog.AdminPasswordDialog
import com.haiheng.voiceandbook.service.DownLoadManagerService
import com.haiheng.voiceandbook.utils.AppUtils
import com.haiheng.voiceandbook.utils.DisplayUtil
import com.haiheng.voiceandbook.utils.FastClickUtil
import com.haiheng.voiceandbook.utils.PermissionsObserver
import com.haiheng.voiceandbook.view.RecyclerViewSpacesItemDecoration
import com.haiheng.voiceandbook.viewmodel.BookViewModel
import com.haiheng.voiceandbook.voice.TracksActivity
import com.tbruyelle.rxpermissions.RxPermissions
import com.ximalaya.ting.android.opensdk.constants.DTransferConstants
import com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest
import com.ximalaya.ting.android.opensdk.datatrasfer.IDataCallBack
import com.ximalaya.ting.android.opensdk.model.album.Album
import com.ximalaya.ting.android.opensdk.model.album.AlbumList
import kotlinx.android.synthetic.main.activity_main.ivWebUrl
import kotlinx.android.synthetic.main.activity_main.ll_ysx
import kotlinx.android.synthetic.main.activity_main.ll_ysx_two
import kotlinx.coroutines.launch


class MainActivity : BaseActivity(), AppBarLayout.OnOffsetChangedListener {
    var pageOneNo: Int = 1
    var pageTwoNo: Int = 1

    var pageThreeNo: Int = 1
    var pageFourNo: Int = 1

    val pageOneSize: Int = 8
    val pageTwoSize: Int = 10
    val pageThreeSize: Int = 10
    val pageFourSize: Int = 10

    //分类
    var categoryId: String = "2"
    var activityMainBinding: ActivityMainBinding? = null

    private var adapter: MainTopAdapter? = null
    private var list: ArrayList<Album> = java.util.ArrayList()

    private var twoAdapter: MainTopAdapter? = null
    private var listTwo: ArrayList<Album> = java.util.ArrayList()

    private var hotAdapter: BookAdapter? = null
    private var hotBookList = mutableListOf<BookDto>()

    private var lastAdapter: BookAdapter? = null
    private var lastBookList = mutableListOf<BookDto>()

    var service: Intent? = null
    /**
     * 数据更新
     */
    override fun initDataChange() {
        bookViewModel?.lastBook?.observe(this, Observer {
            if (it?.data != null && it.data.size > 0) {
                lastAdapter?.setNewData(it.data)
            }
        })

        bookViewModel?.hotBook?.observe(this, Observer {
            if (it?.data != null && it.data.size > 0) {
                hotAdapter?.setNewData(it.data)
            }
        })


    }

    /**
     *  设置事件
     */
    override fun initListener() {

        activityMainBinding?.ivScroll?.setOnClickListener {
            activityMainBinding?.nestedScrollView?.scrollTo(0, 0)
            activityMainBinding?.appBar?.setExpanded(true)

        }
        activityMainBinding?.tvOneNext?.setOnClickListener {
            pageOneNo++
            getAlbumList(categoryId)
            val rotateAnim = AnimationUtils.loadAnimation(this, R.anim.my_tote)
            activityMainBinding!!.ivChangeOne.startAnimation(rotateAnim)

        }
        activityMainBinding?.tvTwoNext?.setOnClickListener {
            pageTwoNo++
            getAlbumListTwo(categoryId)
            val rotateAnim = AnimationUtils.loadAnimation(this, R.anim.my_tote)
            activityMainBinding!!.ivChangeTwo.startAnimation(rotateAnim)
        }
        activityMainBinding?.tvThreeNext?.setOnClickListener {

            pageThreeNo++
            /**
             * 最新书籍
             */
            bookViewModel?.latestRank(pageThreeNo, pageThreeSize)
            val rotateAnim = AnimationUtils.loadAnimation(this, R.anim.my_tote)
            activityMainBinding!!.ivChangeThree.startAnimation(rotateAnim)

        }

        activityMainBinding?.tvFourNext?.setOnClickListener {

            pageFourNo++
            /**
             * 热门图书
             */
            bookViewModel?.hotRank(pageFourNo, pageFourSize)
            val rotateAnim = AnimationUtils.loadAnimation(this, R.anim.my_tote)
            activityMainBinding!!.ivChangeFour.startAnimation(rotateAnim)


        }
        activityMainBinding?.llVoice?.setOnClickListener {
            val intent = Intent(this@MainActivity, SearchActivity::class.java)
            intent.putExtra("type", 0)
            startActivity(intent)
        }
        activityMainBinding?.llBook?.setOnClickListener {
            val intent = Intent(this@MainActivity, SearchActivity::class.java)
            intent.putExtra("type", 1)
            startActivity(intent)

        }
        activityMainBinding?.llVoiceTwo?.setOnClickListener {
            val intent = Intent(this@MainActivity, SearchActivity::class.java)
            intent.putExtra("type", 0)
            startActivity(intent)
        }
        activityMainBinding?.llBookTwo?.setOnClickListener {
            val intent = Intent(this@MainActivity, SearchActivity::class.java)
            intent.putExtra("type", 1)
            startActivity(intent)

        }

        activityMainBinding?.llYsxTwo?.setOnClickListener {
            var intent = Intent(this,WebViewActivity::class.java)
            startActivity(intent)
        }
        activityMainBinding?.llYsx?.setOnClickListener {
            var intent = Intent(this,WebViewActivity::class.java)
            startActivity(intent)
        }
        activityMainBinding?.vSetting?.setOnClickListener {
            if (FastClickUtil.isFastFiveClick(activityMainBinding?.vSetting?.id!!, 1000)) {
                var dialog = AdminPasswordDialog(this@MainActivity);
                dialog.show()
                dialog.setOnPasswordLisener { title, passwod ->
                    if (passwod ==Constants.SETTING_PASSWORD) {
                        var settingDialog = SettingDialog(this)
                        settingDialog.show()
                        dialog.dismiss()
                    } else {
                        Toast.makeText(applicationContext,"密码错误",Toast.LENGTH_SHORT).show()
                        dialog.clearText()
                    }
                }
            }
        }
    }

    /**
     * 初始化成员数据
     */
    override fun initData() {
        for (i in 0 until  10){
            Log.e(TAG, "initData: "+i )
        }
//        activityMainBinding?.tvLibraliTitle?.setText(Constants.getLibraryName())
    }

    override fun onDestroy() {
        super.onDestroy()
        if (service != null) {
            stopService(service)
        }
    }

    override fun onResume() {
        super.onResume()
        activityMainBinding?.tvVersion?.setText(BuildConfig.VERSION_NAME)
        activityMainBinding?.tvLibraliTitle?.setText(Constants.getLibraryName())
        if (Constants.getLibraryCode().equals(Constants.yanjing_code)){
            activityMainBinding?.ivSmallLogo?.visibility = View.VISIBLE
            activityMainBinding?.ivSmallLogo?.setImageResource(R.mipmap.yanjing_logo)
        }else{
            if (TextUtils.isEmpty(Constants.getLibraryLogo())){
                activityMainBinding?.ivSmallLogo?.visibility = View.GONE
            }else{
                activityMainBinding?.ivSmallLogo?.let {
                    activityMainBinding?.ivSmallLogo?.visibility = View.VISIBLE
                    GlideUtils.load(this,Constants.getLibraryLogo(), it)
                }
            }
        }
        if (AppUtils.isNotConnected(MyApplication.getInstance().applicationContext)){
            showTipsDialog(getString(R.string.no_net_hint))
        }else{
            if (requestPermissions(99)){
                VersionManager.getVersionInfo(this@MainActivity,false)
            }
        }
        if (Constants.isOpenYouShengXin()){
//            ivWebUrl.visibility = View.VISIBLE
            ll_ysx.visibility = View.VISIBLE
            ll_ysx_two.visibility = View.VISIBLE
        }else{
//            ivWebUrl.visibility = View.GONE
            ll_ysx.visibility = View.GONE
            ll_ysx_two.visibility = View.GONE
        }



    }

    /**
     * 获取有声书
     */
    private fun getVoiceBook() {
        getAlbumList(categoryId)
        getAlbumListTwo(categoryId)
    }
    /**
     * 获取电子书
     */
    private fun getNetBook() {

        /**
         * 最新书籍
         */
        bookViewModel?.latestRank(pageThreeNo, pageThreeSize)

        /**
         * 热门图书
         */
        bookViewModel?.hotRank(pageFourNo, pageFourSize)


    }

    /**
     * 开始数据业务
     */
    fun initBusiniess() {
        if(service==null){
            service = Intent(this, DownLoadManagerService::class.java)
        }
        startService(service)
        getVoiceBook()
        getNetBook()
    }

    //重新排列布局
    private fun rearrangeCardViews() {
        var config = Constants.getMainOrderConfig()
        // 设置新的布局参数
        val layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        layoutParams.weight = 1f // 调整权重以改变位置

        // 根据配置顺序重新排列 CardView 的位置
        config.forEachIndexed { index, char ->
            val position = char.toString().toInt()
            val cardView = getCardViewByPosition(position)
            if (cardView != null) {
                activityMainBinding?.llMainList?.removeView(cardView)
                activityMainBinding?.llMainList?.addView(cardView, index, layoutParams)
            }
        }
    }
    private fun getCardViewByPosition(position: Int): CardView? {
        return when (position) {
            1 -> activityMainBinding?.cadOne
            2 -> activityMainBinding?.cadTwo
            3 -> activityMainBinding?.cadThree
            4 -> activityMainBinding?.cadFour
            else -> null
        }
    }
    /**
     * 初始化 View
     */
    override fun initView() {
        rearrangeCardViews()
        bookViewModel = ViewModelProvider(
            this,
            ViewModelProvider.NewInstanceFactory()
        ).get(BookViewModel::class.java)
        //首页第一个car片列表
        val hashMapOne = HashMap<String, Int>()
        hashMapOne.put(
            RecyclerViewSpacesItemDecoration.TOP_DECORATION,
            DisplayUtil.dip2px(this, 10f)
        )
        val decorationOne = RecyclerViewSpacesItemDecoration(
            hashMapOne
        )
        activityMainBinding?.rvOne?.addItemDecoration(
            decorationOne
        )

        activityMainBinding?.rvOne?.layoutManager = GridLayoutManager(this, 4)
        adapter = MainTopAdapter(R.layout.item_main, list)
        activityMainBinding?.rvOne?.adapter = adapter
        adapter?.apply {
            openLoadAnimation(BaseQuickAdapter.SCALEIN)//缩放
            setOnItemClickListener { adapter, view, position ->
                val item = adapter.getItem(position) as Album
                val intent = Intent(this@MainActivity, TracksActivity::class.java)
                intent.putExtra("id", item.id.toString())
                val bundle = Bundle()
                bundle.putParcelable("album", item)
                intent.putExtra("bundle", bundle)
                startActivity(intent)
            }


        }

        //首页第二个car片列表
        activityMainBinding?.rvTwo?.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        twoAdapter = MainTopAdapter(R.layout.item_main_two, listTwo)
        activityMainBinding?.rvTwo?.adapter = twoAdapter

        twoAdapter?.apply {
            openLoadAnimation(BaseQuickAdapter.SCALEIN)//缩放
            setOnItemClickListener { adapter, view, position ->
                val item = adapter.getItem(position) as Album
                val intent = Intent(this@MainActivity, TracksActivity::class.java)
                intent.putExtra("id", item.id.toString())
                val bundle = Bundle()
                bundle.putParcelable("album", item)
                intent.putExtra("bundle", bundle)
                startActivity(intent)
            }

        }

        //第二个car片列表
        val hashMapTwo = HashMap<String, Int>()
        hashMapTwo.put(
            RecyclerViewSpacesItemDecoration.TOP_DECORATION,
            DisplayUtil.dip2px(this, 2f)
        )
        val decorationTwo = RecyclerViewSpacesItemDecoration(
            hashMapTwo
        )
        activityMainBinding?.rvTwo?.addItemDecoration(
            decorationTwo
        )
        //首页第三个car片列表
        activityMainBinding?.rvThree?.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        activityMainBinding?.rvThree?.addItemDecoration(
            decorationTwo
        )
        lastAdapter = BookAdapter(R.layout.item_main_three, lastBookList)
        activityMainBinding?.rvThree?.adapter = lastAdapter

        lastAdapter?.apply {
            openLoadAnimation(BaseQuickAdapter.SCALEIN)//缩放
            setOnItemClickListener { adapter, view, position ->
                val item = adapter.getItem(position) as BookDto
                if (AppUtils.isNotConnected(MyApplication.getInstance().applicationContext)){
                    showTipsDialog(getString(R.string.no_net_hint))
                }else{
                    getBooKDetail(item.getBookId())
                }

            }

        }

        //首页第四个car片列表
        activityMainBinding?.rvFour?.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        activityMainBinding?.rvFour?.addItemDecoration(
            decorationTwo
        )
        hotAdapter = BookAdapter(R.layout.item_main_three, hotBookList)
        activityMainBinding?.rvFour?.adapter = hotAdapter
        hotAdapter?.apply {
            openLoadAnimation(BaseQuickAdapter.SCALEIN)//缩放
            setOnItemClickListener { adapter, view, position ->
                val item = adapter.getItem(position) as BookDto
                if (AppUtils.isNotConnected(MyApplication.getInstance().applicationContext)){
                    showTipsDialog(getString(R.string.no_net_hint))
                }else{
                    getBooKDetail(item.getBookId())
                }
            }

        }
        activityMainBinding?.appBar?.addOnOffsetChangedListener(this)

        RxPermissions.getInstance(this).request(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE

        ).subscribe(object : PermissionsObserver() {
            override fun onGetPermissionsSuccess() {
                initBusiniess()
            }
            override fun onGetPermissionsSuccessFailuer() {
                finish()
            }
        })


        ivWebUrl.setOnClickListener {
            var intent = Intent(this,WebViewActivity::class.java)
            startActivity(intent)
        }
    }

    /**
     * 获取书籍详情信息
     */
    private fun getBooKDetail(bookId: Long) {
        lifecycleScope.launch {
            showLoadingDialog()
            val bookDetail = bookViewModel?.getBookDetail(bookId)
            hideLoadingDialog()
            if (bookDetail == null){
                if (AppUtils.isNotConnected(MyApplication.getInstance().applicationContext)){
                    showTipsDialog(getString(R.string.no_net_hint))
                }else{
                    showTipsDialog(getString(R.string.get_book_info_fail))
                }
            }else{
                showBookDetailDialog(bookDetail)
            }
        }

    }

    /**
     * 初始化布局
     */
    override fun intiLayout() {
        activityMainBinding = ActivityMainBinding.inflate(LayoutInflater.from(this))
        setContentView(activityMainBinding?.getRoot())

    }


    /**
     * 喜马拉雅的sdk接口
     * 根据分类和标签获取某个分类某个标签下的专辑列表
     * （最火/最新/最多播放）
     */
    private fun getAlbumList(categoryId: String) {
        val map = HashMap<String, String>()
        //分类ID，指定分类，为0时表示热门分类 2 = 音乐
        map[DTransferConstants.CATEGORY_ID] = categoryId
        //分类下对应的专辑标签，不填则为热门分类
//        map[DTransferConstants.TAG_NAME] = intent.getStringExtra("tagName")!!
        map[DTransferConstants.CALC_DIMENSION] = "1"//计算维度，现支持最火（1），最新（2），经典或播放最多（3）
        //返回第几页，必须大于等于1，不填默认为1
        map.put(DTransferConstants.PAGE, pageOneNo.toString())
        //每页多少条，默认20，最多不超过200
        map.put(DTransferConstants.PAGE_SIZE, pageOneSize.toString())

        CommonRequest.getAlbumList(map, object : IDataCallBack<AlbumList> {

            override fun onError(p0: Int, p1: String?) {
                hideLoadingDialog()
                if (pageOneNo > 1) {
                    pageOneNo--
                }
                Toast.makeText(this@MainActivity, "系统异常：${p1}", Toast.LENGTH_SHORT).show()
            }

            override fun onSuccess(p0: AlbumList?) {
                hideLoadingDialog()
                if (p0 != null && p0.albums != null && p0.albums.size > 0) {
                    list.clear()
                    list.addAll(p0!!.albums)
                    adapter?.notifyDataSetChanged()
                } else {
                    if (pageOneNo > 1) {
                        pageOneNo--
                    }
                }
            }

        })
    }

    /**
     * 喜马拉雅的sdk接口
     * 根据分类和标签获取某个分类某个标签下的专辑列表
     * （最火/最新/最多播放）
     */
    private fun getAlbumListTwo(categoryId: String) {

        val map = HashMap<String, String>()
        //分类ID，指定分类，为0时表示热门分类
        map[DTransferConstants.CATEGORY_ID] = categoryId
        //分类下对应的专辑标签，不填则为热门分类
//        map[DTransferConstants.TAG_NAME] = intent.getStringExtra("tagName")!!
        map[DTransferConstants.CALC_DIMENSION] = "2"//计算维度，现支持最火（1），最新（2），经典或播放最多（3）
        //返回第几页，必须大于等于1，不填默认为1
        map.put(DTransferConstants.PAGE, pageTwoNo.toString())
        //每页多少条，默认20，最多不超过200
        map.put(DTransferConstants.PAGE_SIZE, pageTwoSize.toString())

        CommonRequest.getAlbumList(map, object : IDataCallBack<AlbumList> {

            override fun onError(p0: Int, p1: String?) {
                hideLoadingDialog()
                if (pageTwoNo > 1) {
                    pageTwoNo--
                }
                Toast.makeText(this@MainActivity, "系统异常：${p1}", Toast.LENGTH_SHORT).show()
            }

            override fun onSuccess(p0: AlbumList?) {
                hideLoadingDialog()
                if (p0 != null && p0.albums != null && p0.albums.size > 0) {
                    listTwo.clear()
                    listTwo.addAll(p0!!.albums)
                    twoAdapter?.notifyDataSetChanged()
                } else {
                    if (pageTwoNo > 1) {
                        pageTwoNo--
                    }
                }
            }

        })
    }

    //AppBarLayout的监听方法
    override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
        //720*1080手机 verticalOffset取值范围[0-200]px
        //720*1080手机 verticalOffset取值范围[0-200]px
        val absVerticalOffset = Math.abs(verticalOffset).toFloat() //AppBarLayout竖直方向偏移距离px

        val totalScrollRange = appBarLayout.totalScrollRange.toFloat() //AppBarLayout总的距离px

        //滑动超出了
        if (absVerticalOffset >= DisplayUtil.dip2px(this, 75f)) {
            activityMainBinding?.llBottom?.setVisibility(View.VISIBLE)
            activityMainBinding?.llTop?.setVisibility(View.INVISIBLE)
        } else {

            activityMainBinding?.llBottom?.setVisibility(View.INVISIBLE)
            activityMainBinding?.llTop?.setVisibility(View.VISIBLE)
        }
        val px = absVerticalOffset / totalScrollRange


    }

    /** 根据百分比改变颜色透明度  */
    fun changeAlpha(color: Int, fraction: Float): Int {
        Log.e("MainActivity", "fraction: $fraction")
        val red = Color.red(color)
        val green = Color.green(color)
        val blue = Color.blue(color)
        val alpha = (Color.alpha(color) * fraction).toInt()
        return Color.argb(alpha, red, green, blue)
    }


    fun requestPermissions(requestCode: Int):Boolean {
        try {
            if (Build.VERSION.SDK_INT >= 23) {
                val requestPerssionArr = ArrayList<String>()
//                val hasCamrea = checkSelfPermission(Manifest.permission.CAMERA)
//                if (hasCamrea != PackageManager.PERMISSION_GRANTED) {
//                    requestPerssionArr.add(Manifest.permission.CAMERA)
//                }
                val hasSdcardRead = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                if (hasSdcardRead != PackageManager.PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.READ_EXTERNAL_STORAGE)
                }
                val hasSdcardWrite = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                if (hasSdcardWrite != PackageManager.PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                }
                // 是否应该显示权限请求
                if (requestPerssionArr.size >= 1) {
                    val requestArray = arrayOfNulls<String>(requestPerssionArr.size)
                    for (i in requestArray.indices) {
                        requestArray[i] = requestPerssionArr[i]
                    }
                    requestPermissions(requestArray, requestCode)
                    return false
                }else{
                    return true
                }

            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }


}